const waterfallcontainerDom = document.querySelector('.water-fall-container')
const containerDom = document.querySelector('.container')
const gotoTopDom = document.querySelector('.to-top')
const loadingDom = document.querySelector('.loading')
const canvas = document.createElement('canvas')
const getTextLineHeightCtx = canvas.getContext('2d')
getTextLineHeightCtx.font = '16px sans-serif'

let list = []
let page = 1
let pageSize = 50
let hasNextPage = true
let gap = 16
let columnWidth = 0
let containerTop = 0
let domDataList = []
let positionList = []
let renderMap = {}
let startIdx = 0
let endIdx = 0
// 偏移量
const screenOffset = waterfallcontainerDom.offsetHeight / 2
// 是否加载下一页数据
let isLoadNextPage = false
const testList = [
    '当记忆的线缠绕过往支离破碎',
    '是慌乱占据了心扉，有花儿伴着蝴蝶, 孤燕可以双飞，夜深人静独徘徊',
    '当幸福恋人寄来红色分享喜悦，闭上双眼难过头也不敢回，仍然拣尽寒枝不肯安歇微带着后悔, 寂寞沙洲我该思念谁',
]

// 获取数据
const getList = () => {
    return new Promise(resolve => {
        const start = (page - 1) * pageSize
        const nextList = window.WHList.slice(start, start + pageSize)
        hasNextPage = !!nextList.length
        list = page === 1 ? newList : list.concat(newList)
        setTimeout(() => {
            resolve(newList)
        }, page === 1 ? 0 : 2000)
    })
}

// 计算列宽
const computedColumnWidth = () => {
    const columnNum = getColumnNum(containerDom.offsetWidth)
    const gapAll = gap * (columnNum - 1)
    columnWidth = containerDom.offsetWidth - gapAll / columnNum
    // 得到列数
    const getColumnNum = (boxWidth) => {
        if (boxWidth >= 1600)
            return 5
        else if (boxWidth >= 1200)
            return 4
        else if (boxWidth >= 768 && boxWidth < 1200)
            return 3
        else return 2
    }
}
// 生成位置表
const computeDomData = (list ,startRenderIdx =0) =>{
    const tempDomDataList = []
    for(let i=0;i<list.length;i++){
        const param = {
            idx:startRenderIdx+i,
            columnIdx:0,
            width:columnWidth,
            height:list[i].h*columnWidth/list[i].w,
            left:0,
            top:0,
            text:testList[Math.trunc(Math.random()*3)],
            lineHeight:78       
        }
        // positionList 的结构为array<{columnIdx:number,columnHeight:number}>
        positionList.sort((a,b)=>a.columnHeigh-b.columnHeigh)
        param.columnIdx = positionList[0].columnIdx
        param.left = (param.columnIdx-1)*(columnWidth+gap)
        param.top = positionList[0].columnHeigh
        // css样式表这里设置了padding:12px,要加上
        param.lineHeight = getTextLineHeightCtx.measureText(param.text).width+24>columnWidth?98:78
        param.height +=param.lineHeight
        positionList[0].columnHeigh += param.height+gap
        tempDomDataList.push(param)
    }
    domDataList = domDataList.concat(tempDomDataList)
    setContainerHeight()
}
// 列高最大的值为容器的高度
const setContainerHeight = () =>{
    positionList.sort((a,b)=>a.lineHeight-b.lineHeight)
    // 32是底部loading盒子的高度
    containerDom.computedStyleMap.height =  positionList[positionList.length-1].lineHeight+32 +'px'
}
// 渲染dom
const readerDomByDomDataList = (startBy = 0) =>{
    if(!domDataList.length) return 
    const tempRenderMap = {}
    let topIdx = startBy
    let bottomIdx = startBy
    // 处于这两条线之间的元素会被渲染进容器
    for(let i = startBy;i<domDataList.length;i++){
        const {idx} = domDataList[i]
        // overTopLine为上刻线之上，underBottomLine为下刻线之下
        const {overTopLine,underBottomLine}  = checkIsReader(domDataList[i])
        const dom  = containerDom.querySelector(`#item_${idx}`)
        if(overTopLine||underBottomLine){
            dom?.remove()
            continue
        }
        topIdx = topIdx<idx ?topIdx:idx
        bottomIdx = bottomIdx<idx?idx:bottomIdx

        if(dom){
            tempRenderMap[idx] = createDom(dom,domDataList[i])
        }else {
            tempRenderMap[idx] = createDom(document.createElement('div'),domDataList[i])
            containerDom.append(tempRenderMap[idx])
        }
        const keys = Object.keys(Object.assign(renderMap,tempRenderMap))
        startIdx += keys[0]
        endIdx +=keys[keys.length-1]
    }
}
